<template>
  <div class="container">
    <!-- 头部区域 -->
    <div class="header">
      <!-- 返回按钮 -->
      <button class="back-button" @click="goHome">
        <font-awesome-icon :icon="['fas', 'chevron-left']" />
        返回首页
      </button>

      <div class="logo">
        <font-awesome-icon :icon="['fas', 'chart-line']" />
        视频关注分析平台
      </div>
      <p class="text-muted">实时追踪视频表现，深度分析数据变化</p>
    </div>

    <!-- 视频信息区域 -->
    <div class="video-header">
      <div class="video-cover">
        <img :src="img" v-if="img" />
        <div class="cover-placeholder" v-else>
          <font-awesome-icon :icon="['fas', 'video']" size="2x" />
          <p>视频封面加载中...</p>
        </div>
      </div>
      <div class="video-info">
        <h2 class="video-title">
          {{ videoData.title || '加载中...' }}
        </h2>
        <div class="video-meta">
          <div class="meta-item">
            <div class="meta-label">BV号</div>
            <div class="meta-value">{{ bvid }}</div>
          </div>
          <div class="meta-item">
            <div class="meta-label">发布时间</div>
            <div class="meta-value">{{ formatDate(videoData.pubdate) }}</div>
          </div>
          <div class="meta-item">
            <div class="meta-label">分类</div>
            <div class="meta-value">{{ videoData.tname || '加载中...' }}</div>
          </div>
          <div class="meta-item">
            <div class="meta-label">时长</div>
            <div class="meta-value">{{ duration || '加载中...' }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <h3 class="panel-title">
        <font-awesome-icon :icon="['fas', 'sliders-h']" /> 分析控制面板
      </h3>

      <div class="metrics-selector">
        <div
          class="metric-btn"
          v-for="metric in metrics"
          :key="metric.id"
          :class="{ active: selectedMetric === metric.id }"
          @click="selectMetric(metric.id)"
        >
          <font-awesome-icon :icon="metric.icon" />
          {{ metric.name }}
        </div>
      </div>

      <div class="d-flex justify-content-between align-items-center">
        <div class="time-range">
          <div
            class="time-btn"
            v-for="range in timeRanges"
            :key="range.value"
            :class="{ active: timeRange === range.value }"
            @click="selectTimeRange(range.value)"
          >
            {{ range.label }}
          </div>
        </div>

        <div class="text-muted">
          <font-awesome-icon :icon="['fas', 'sync-alt']" /> 数据每5分钟自动更新
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="spinner-container">
        <font-awesome-icon :icon="['fas', 'spinner']" spin size="3x" />
        <p>加载视频数据中...</p>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="metrics-cards" v-if="!loading">
      <div class="metric-card" v-for="card in metricCards" :key="card.id">
        <div class="card-header">
          <div class="card-title">{{ card.title }}</div>
          <div class="card-icon">
            <font-awesome-icon :icon="card.icon" />
          </div>
        </div>
        <div class="card-value">{{ formatNumber(card.value) }}</div>
        <div
          class="card-change"
          :class="card.change >= 0 ? 'positive' : 'negative'"
        >
          <font-awesome-icon
            :icon="card.change >= 0 ? ['fas', 'arrow-up'] : ['fas', 'arrow-down']"
          />
          {{ Math.abs(card.change) }}% {{ card.change >= 0 ? '增长' : '下降' }}
          (较上小时)
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container" v-if="!loading">
      <h3 class="chart-title">
        <font-awesome-icon :icon="['fas', 'chart-line']" />
        {{ selectedMetricName }} 变化趋势 ({{ timeRangeLabel }})
      </h3>
      <canvas ref="chartCanvas"></canvas>
    </div>

    <!-- 数据分析区域 -->
    <div class="analysis-container" v-if="!loading">
      <h3 class="section-title">
        <font-awesome-icon :icon="['fas', 'lightbulb']" /> 数据分析洞察
      </h3>

      <div class="analysis-content">
        <p>基于当前数据，我们对视频表现进行了深度分析：</p>

        <div class="insight-card">
          <div class="insight-title">
            <font-awesome-icon :icon="['fas', 'rocket']" /> 增长趋势分析
          </div>
          <p>
            过去{{ timeRangeLabel.toLowerCase() }}，视频{{ selectedMetricName
            }}呈现{{ growthTrend }}趋势。{{ growthDescription }}
          </p>
        </div>

        <div class="insight-card">
          <div class="insight-title">
            <font-awesome-icon :icon="['fas', 'bolt']" /> 高峰时段分析
          </div>
          <p>{{ peakAnalysis }}</p>
        </div>

        <div class="insight-card">
          <div class="insight-title">
            <font-awesome-icon :icon="['fas', 'bullseye']" /> 优化建议
          </div>
          <p>{{ optimizationAdvice }}</p>
        </div>

        <p class="mt-4">
          持续关注这些指标变化，可以帮助您更好地理解视频表现，制定有效的推广策略。
        </p>
      </div>
    </div>

    <!-- API状态提示 -->
    <div v-if="apiStatusMessage" class="api-status">
    <div class="api-alert" :class="{ error: apiStatusIcon === 'exclamation-triangle' }">
      <font-awesome-icon :icon="['fas', apiStatusIcon]" />
      {{ apiStatusMessage }}
    </div>
  </div>

    <!-- 悬浮关注按钮 -->
    <FloatingFollow />
  </div>
  <router-view :key="$route.fullPath" />
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { library } from '@fortawesome/fontawesome-svg-core';
import {
  faChartLine,
  faSlidersH,
  faSyncAlt,
  faEye,
  faThumbsUp,
  faCoins,
  faStar,
  faShareAlt,
  faArrowUp,
  faArrowDown,
  faLightbulb,
  faRocket,
  faBolt,
  faBullseye,
  faChevronLeft,
  faSpinner,
  faVideo,
  faExclamationTriangle,
  faInfoCircle
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import Chart from 'chart.js/auto';
import FloatingFollow from '@/components/FloatingFollow.vue';
import {
  getVideoBasicInfo,
  getVideoViewsChange,
  getVideoCoinsChange,
  getVideoSharesChange,
  getVideoFavoritesChange
} from '@/api/video.js';
import { useUserStore } from '@/store/user.js';

// 添加图标库
library.add(
  faChartLine,
  faSlidersH,
  faSyncAlt,
  faEye,
  faThumbsUp,
  faCoins,
  faStar,
  faShareAlt,
  faArrowUp,
  faArrowDown,
  faLightbulb,
  faRocket,
  faBolt,
  faBullseye,
  faChevronLeft,
  faSpinner,
  faVideo,
  faExclamationTriangle,
  faInfoCircle
);

// 路由和状态管理
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 响应式状态
const bvid = ref('');
const videoData = ref({
  title: '',
  tname: '',
  pubdate: 0,
  view: 0,
  like: 0,
  coin: 0,
  favorite: 0,
  duration: 0
});
const img = ref('');
const loading = ref(true);
const chartInstance = ref(null);
const chartCanvas = ref(null);
const apiStatusMessage = ref('');
const apiStatusIcon = ref('info-circle');
const apiStatusTimeout = ref(null);

// 图表数据存储
const chartData = ref({
  views: { labels: [], data: [] },
  coins: { labels: [], data: [] },
  shares: { labels: [], data: [] },
  favorites: { labels: [], data: [] }
});

// 指标和时间范围
const metrics = ref([
  { id: 'views', name: '播放量', icon: ['fas', 'eye'] },
  { id: 'coins', name: '投币数', icon: ['fas', 'coins'] },
  { id: 'favorites', name: '收藏数', icon: ['fas', 'star'] },
  { id: 'shares', name: '分享数', icon: ['fas', 'share-alt'] }
]);

const timeRanges = ref([
  { label: '24小时', value: 24 },
  { label: '7天', value: 168 },
]);

const selectedMetric = ref('views');
const timeRange = ref(24);
const updateInterval = ref(null);

// 指标卡片数据
const metricCards = ref([
  { id: 1, title: '播放量', icon: ['fas', 'eye'], value: 0, change: 0 },
  { id: 2, title: '投币数', icon: ['fas', 'coins'], value: 0, change: 0 },
  { id: 3, title: '收藏数', icon: ['fas', 'star'], value: 0, change: 0 },
  { id: 4, title: '分享数', icon: ['fas', 'share-alt'], value: 0, change: 0 }
]);

// 计算属性
const selectedMetricName = computed(() => {
  const metric = metrics.value.find((m) => m.id === selectedMetric.value);
  return metric ? metric.name : '';
});

const timeRangeLabel = computed(() => {
  const range = timeRanges.value.find((r) => r.value === timeRange.value);
  return range ? range.label : '';
});

const growthTrend = computed(() => {
  if (selectedMetric.value === 'views') return '稳定增长';
  if (selectedMetric.value === 'coins') return '波动上升';
  if (selectedMetric.value === 'favorites') return '稳步提升';
  return '稳定发展';
});

const growthDescription = computed(() => {
  if (timeRange.value === 24) {
    return '在最近24小时内，该指标平均每小时增长2.1%，其中在18:00-20:00时段增长最为显著。';
  } else if (timeRange.value === 168) {
    return '过去一周该指标总体呈现上升趋势，周末的增长速度明显高于工作日。';
  } else {
    return '过去一个月该指标增长了28.5%，其中第三周的增长最为突出，可能与相关热点事件有关。';
  }
});

const peakAnalysis = computed(() => {
  if (selectedMetric.value === 'views') {
    return '播放量在每天的18:00-22:00达到高峰，最高峰值出现在周六晚上20:30左右。';
  } else if (selectedMetric.value === 'coins') {
    return '投币行为集中在视频的后半段，特别是在视频结束前的5分钟，投币率明显提升。';
  } else if (selectedMetric.value === 'favorites') {
    return '收藏行为在视频发布后的前3小时最为集中，之后逐渐趋于平稳。';
  } else {
    return '分享行为在视频发布后1-2小时达到高峰，之后逐渐下降。';
  }
});

const optimizationAdvice = computed(() => {
  if (selectedMetric.value === 'views') {
    return '建议在18:00-20:00高峰时段进行推广，同时优化视频标题和封面以提高点击率。';
  } else if (selectedMetric.value === 'coins') {
    return '在视频后半段加入投币引导，强调内容价值，可设置投币目标奖励。';
  } else if (selectedMetric.value === 'favorites') {
    return '增加视频的实用性和收藏价值，在关键内容处提示观众收藏。';
  } else {
    return '优化分享按钮位置，添加社交分享激励，如"分享后解锁隐藏内容"。';
  }
});

const duration = computed(() => {
  if (!videoData.value.duration) return '加载中...';
  const mins = Math.floor(videoData.value.duration / 60);
  const secs = videoData.value.duration % 60;
  return `${mins}分${secs}秒`;
});

// 方法
const goHome = () => {
  router.push({ name: 'home' });
};

const formatDate = (timestamp) => {
  if (!timestamp) return '加载中...';
  const date = new Date(timestamp * 1000);
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
};

const selectMetric = (metricId) => {
  selectedMetric.value = metricId;
};

const selectTimeRange = (range) => {
  timeRange.value = range;
};

const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 关键修复：聚合小时级数据


// 关键修复：聚合天级数据
const aggregateDailyData = (data) => {
  const aggregated = {};

  data.forEach(item => {
    const date = new Date(item.date);
    // 创建按天分组的键：YYYY-MM-DD
    const dayKey = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;

    if (!aggregated[dayKey]) {
      aggregated[dayKey] = {
        count: 0,
        value: 0,
        timestamp: date
      };
    }

    // 累加该天内的所有值
    aggregated[dayKey].value += item.value;
    aggregated[dayKey].count++;
  });

  // 转换为数组并按时间排序
  return Object.values(aggregated)
    .map(item => ({
      ...item,
      // 计算该天的平均值
      value: Math.round(item.value / item.count)
    }))
    .sort((a, b) => a.timestamp - b.timestamp);
};

// 获取图表数据
// 获取图表数据
const fetchChartData = async (metricType) => {
  try {
    let response;
    switch (metricType) {
      case 'views':
        response = await getVideoViewsChange(bvid.value);
        break;
      case 'coins':
        response = await getVideoCoinsChange(bvid.value);
        break;
      case 'shares':
        response = await getVideoSharesChange(bvid.value);
        break;
      case 'favorites':
        response = await getVideoFavoritesChange(bvid.value);
        break;
      default:
        return;
    }

    if (response.data.code === 200) {
      // 获取当前时间（本地时间）
      const now = new Date();

      // 计算时间范围截止点（本地时间）
      const cutoffTime = now.getTime() - timeRange.value * 3600 * 1000; // 小时转毫秒

      // 处理原始数据并转换为本地时间
      const rawPoints = response.data.data
        .map(item => {
          // 将GMT日期字符串转换为本地时间
          const dateObj = new Date(item.date);
          const timestamp = dateObj.getTime();
          const localDate = new Date(timestamp);

          // 获取指标值
          let value;
          switch (metricType) {
            case 'views':
              value = item.view_count;
              break;
            case 'coins':
              value = item.coin_count;
              break;
            case 'shares':
              value = item.share_count;
              break;
            case 'favorites':
              value = item.favorite_count;
              break;
            default:
              value = 0;
          }

          return {
            timestamp, // 本地时间戳
            localDate, // 本地日期对象
            date: item.date, // 原始GMT日期字符串
            value: value
          };
        })
        // 筛选最新时间范围内的数据（本地时间）
        .filter(item => item.timestamp >= cutoffTime)
        // 按时间顺序排序（从早到晚）
        .sort((a, b) => a.timestamp - b.timestamp);

      // 聚合数据
      let aggregatedData;
      let labels = [];
      let dataPoints = [];

      if (timeRange.value === 24) {
        // 24小时范围：按小时聚合
        aggregatedData = aggregateHourlyData(rawPoints);

        // 提取标签和数据
        aggregatedData.forEach(item => {
          const date = new Date(item.timestamp);
          labels.push(`${date.getHours().toString().padStart(2, '0')}:00`);
          dataPoints.push(item.value);
        });
      } else {
        // 7天范围：按天聚合
        aggregatedData = aggregateDailyData(rawPoints);

        // 提取标签和数据
        aggregatedData.forEach(item => {
          const date = new Date(item.timestamp);
          labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
          dataPoints.push(item.value);
        });
      }

      // 更新图表数据
      chartData.value[metricType] = { labels, data: dataPoints };

      // 调试日志（可选）
      console.debug(`[${metricType}] 原始数据点:`, rawPoints.map(p => ({
        GMT时间: p.date,
        本地时间: p.localDate.toLocaleString(),
        值: p.value
      })));

      console.debug(`[${metricType}] 聚合数据:`, aggregatedData.map(a => ({
        时间: new Date(a.timestamp).toLocaleTimeString(),
        值: a.value
      })));

    } else {
      console.error(`获取${metricType}数据失败:`, response.data.message);
      showApiStatus(`获取${selectedMetricName.value}数据失败: ${response.data.message || '未知错误'}`, 'error');
    }
  } catch (error) {
    console.error(`获取${metricType}数据出错:`, error);
    showApiStatus(`获取${selectedMetricName.value}数据出错，请稍后重试`, 'error');
  }
};

// 按小时聚合数据（使用本地时间）
const aggregateHourlyData = (data) => {
  const aggregated = {};

  data.forEach(item => {
    const date = new Date(item.timestamp);
    // 创建基于本地时间的分组键（年-月-日-小时）
    const hourKey = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}-${date.getHours().toString().padStart(2, '0')}`;

    if (!aggregated[hourKey]) {
      // 使用该小时第一个数据点的时间作为代表时间
      aggregated[hourKey] = {
        count: 0,
        value: 0,
        timestamp: item.timestamp
      };
    }

    aggregated[hourKey].value += item.value;
    aggregated[hourKey].count++;
  });

  return Object.values(aggregated)
    .map(item => ({
      timestamp: item.timestamp,
      value: Math.round(item.value / item.count) // 计算小时平均值
    }))
    .sort((a, b) => a.timestamp - b.timestamp); // 确保按时间排序
};

// 按天聚合数据（使用本地时间）

// 生成图表数据
const generateChartData = () => {
  const metricType = selectedMetric.value;
  const data = chartData.value[metricType];

  // 如果没有数据，返回空
  if (!data || data.labels.length === 0 || data.data.length === 0) {
    return { labels: [], data: [] };
  }

  // 直接返回聚合后的数据
  return {
    labels: data.labels,
    data: data.data
  };
};

// 初始化图表
const initChart = () => {
  if (!chartCanvas.value) return;

  if (chartInstance.value) {
    chartInstance.value.destroy();
  }

  const ctx = chartCanvas.value.getContext('2d');
  const chartData = generateChartData();

  // 如果数据为空，显示提示
  if (chartData.labels.length === 0) {
    showApiStatus('没有可用的图表数据', 'info');
    return;
  }

  // 动态调整X轴标签显示密度
  const xAxisCallback = (value, index) => {
    // 根据数据点数量调整标签显示密度
    const totalPoints = chartData.labels.length;

    if (timeRange.value === 24) {
      // 24小时范围：每4个点显示一个标签
      return index % 4 === 0 ? value : null;
    } else {
      // 7天范围：根据数据点数量动态调整
      if (totalPoints <= 7) {
        // 数据点少时全部显示
        return value;
      } else if (totalPoints <= 14) {
        // 数据点中等时每隔一个显示
        return index % 2 === 0 ? value : null;
      } else {
        // 数据点多时每隔三个显示
        return index % 3 === 0 ? value : null;
      }
    }
  };

  chartInstance.value = new Chart(ctx, {
    type: 'line',
    data: {
      labels: chartData.labels,
      datasets: [
        {
          label: selectedMetricName.value,
          data: chartData.data,
          borderColor: '#4361ee',
          backgroundColor: 'rgba(67, 97, 238, 0.1)',
          borderWidth: 4,
          pointRadius: 5,
          pointBackgroundColor: '#fff',
          pointBorderColor: '#4361ee',
          pointBorderWidth: 2,
          tension: 0.3,
          fill: true
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          titleColor: '#2b2d42',
          bodyColor: '#2b2d42',
          borderColor: '#e6f0ff',
          borderWidth: 1,
          padding: 12,
          boxPadding: 6,
          usePointStyle: true,
          callbacks: {
            label: (ctx) =>
              `${selectedMetricName.value}: ${formatNumber(ctx.parsed.y)}`
          }
        }
      },
      scales: {
        x: {
          grid: { color: 'rgba(230, 240, 255, 0.5)' },
          ticks: {
            color: '#8d99ae',
            maxRotation: 0,
            callback: xAxisCallback
          }
        },
        y: {
          grid: { color: 'rgba(230, 240, 255, 0.5)' },
          ticks: {
            color: '#8d99ae',
            callback: (v) =>
              v >= 1000000
                ? (v / 1000000).toFixed(1) + 'M'
                : v >= 1000
                ? (v / 1000).toFixed(1) + 'K'
                : v
          }
        }
      },
      animation: { duration: 1000, easing: 'easeOutQuart' }
    }
  });
};

// 显示API状态消息
const showApiStatus = (message, type = 'info') => {
  clearTimeout(apiStatusTimeout.value);
  apiStatusMessage.value = message;
  apiStatusIcon.value = type === 'error' ? 'exclamation-triangle' : 'info-circle';

  // 5秒后自动隐藏
  apiStatusTimeout.value = setTimeout(() => {
    apiStatusMessage.value = '';
  }, 5000);
};

// 从路由获取BV号并加载数据
const loadVideoData = async () => {
  try {
    loading.value = true;
    bvid.value = route.params.bvid;

    if (!bvid.value) {
      console.error('BV号无效');
      showApiStatus('BV号无效，请返回首页重新选择视频', 'error');
      return;
    }

    const response = await getVideoBasicInfo(bvid.value);

    if (response.data.code === 200) {
      videoData.value = response.data.data;

      // 添加URL编码确保特殊字符正确处理
      img.value = `/api/proxy/img?url=${encodeURIComponent(videoData.value.pic || '')}`;

      // 更新指标卡片数据
      metricCards.value[0].value = videoData.value.view || 0;
      metricCards.value[1].value = videoData.value.coin || 0;
      metricCards.value[2].value = videoData.value.favorite || 0;
      metricCards.value[3].value = videoData.value.share || 0;

      showApiStatus('视频基本信息加载成功');
    } else {
      console.error('获取视频数据失败:', response.data.message);
      showApiStatus(`视频基本信息加载失败: ${response.data.message || '未知错误'}`, 'error');
    }
  }
  catch (error) {
    console.error('请求视频数据出错:', error);
    showApiStatus('视频基本信息加载失败，请稍后重试', 'error');
  } finally {
    loading.value = false;
  }
};

// 初始化数据更新定时器
const initDataUpdate = () => {
  if (updateInterval.value) {
    clearInterval(updateInterval.value);
  }

  updateInterval.value = setInterval(async () => {
    // 更新当前选中的指标数据
    await fetchChartData(selectedMetric.value);
    initChart();
    showApiStatus('数据已更新', 'info');
  }, 300000); // 5分钟更新一次
};

// 监听器
watch([selectedMetric, timeRange], async () => {
  // 当切换指标或时间范围时，重新获取数据
  await fetchChartData(selectedMetric.value);
  initChart();
});

watch(() => route.params.bvid, (newBvid) => {
  if (newBvid) {
    loadVideoData();
  }
});

// 生命周期钩子
onMounted(async () => {
  await loadVideoData();

  // 并行获取所有图表数据
  await Promise.all([
    fetchChartData('views'),
    fetchChartData('coins'),
    fetchChartData('shares'),
    fetchChartData('favorites')
  ]);

  initChart();
  initDataUpdate();
});

onBeforeUnmount(() => {
  if (updateInterval.value) {
    clearInterval(updateInterval.value);
  }
  if (chartInstance.value) {
    chartInstance.value.destroy();
  }
  clearTimeout(apiStatusTimeout.value);
});
</script>




<style scoped>
/* 应用 VideoView (2).vue 的样式 */
:root {
  --primary: #4361ee;
  --primary-light: #4895ef;
  --secondary: #3f37c9;
  --accent: #f72585 !important;
  --success: #4cc9f0;
  --dark: #2b2d42;
  --light: #f8f9fa;
  --gray: #8d99ae;
  --card-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

body {
  background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
  color: #333;
  min-height: 100vh;
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 60px 0 20px;
  position: relative;
}

.back-button {
  position: absolute;
  top: 30px;
  left: 0;
  padding: 10px 20px;
  background: linear-gradient(135deg, var(--primary), var(--secondary));
  color: white;
  border: none;
  border-radius: 50px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
  z-index: 10;
}

.back-button:hover {
  background: linear-gradient(135deg, var(--accent), #ff6b9c);
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(247, 37, 133, 0.4);
}

.back-button:active {
  transform: translateY(1px);
}

.logo {
  font-size: 2.8rem;
  font-weight: 800;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  background: linear-gradient(135deg, var(--primary), var(--accent));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: translateY(-3px);
}

.video-header {
  background: white;
  border-radius: 24px;
  box-shadow: var(--card-shadow);
  padding: 25px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  gap: 30px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
}

.video-header:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.video-cover {
  width: 280px;
  height: 160px;
  border-radius: 16px;
  background: linear-gradient(135deg, #e0e7ff 0%, #d1e3ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: var(--primary);
  font-weight: 700;
  box-shadow: 0 8px 20px rgba(67, 97, 238, 0.15);
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.video-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: var(--primary);
  gap: 10px;
  z-index: 2;
}

.video-info {
  flex: 1;
}

.video-title {
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 15px;
  color: var(--dark);
  line-height: 1.4;
}

.video-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 15px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  padding: 12px 15px;
  background: #f7faff;
  border-radius: 14px;
  border: 1px solid #e6f0ff;
  min-width: 140px;
}

.meta-label {
  font-size: 14px;
  color: var(--gray);
  margin-bottom: 5px;
  font-weight: 600;
}

.meta-value {
  font-weight: 700;
  font-size: 16px;
  color: var(--dark);
}

.control-panel {
  background: white;
  border-radius: 20px;
  box-shadow: var(--card-shadow);
  padding: 25px;
  margin-bottom: 30px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
}

.control-panel:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.panel-title {
  font-size: 22px;
  font-weight: 700;
  margin-bottom: 20px;
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 10px;
}

.metrics-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 25px;
}

.metric-btn {
  padding: 10px 20px;
  border-radius: 50px;
  background: #f0f7ff;
  border: 1px solid #d1e3ff;
  color: var(--primary);
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
  display: flex;
  align-items: center;
  gap: 8px;
}

.metric-btn.active, .metric-btn:hover {
  background: linear-gradient(135deg, var(--primary), var(--secondary));
  color: white;
  border-color: var(--primary);
}

.time-range {
  display: flex;
  gap: 15px;
  align-items: center;
}

.time-btn {
  padding: 8px 20px;
  border-radius: 50px;
  background: #f0f7ff;
  border: 1px solid #d1e3ff;
  color: var(--gray);
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
}

.time-btn.active, .time-btn:hover {
  background: var(--primary);
  color: white;
  border-color: var(--primary);
}

.metrics-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.metric-card {
  background: white;
  border-radius: 20px;
  box-shadow: var(--card-shadow);
  padding: 25px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
  position: relative;
  overflow: hidden;
}

.metric-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.metric-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, var(--primary), var(--accent));
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #eef2ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary);
  font-size: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: var(--dark);
}

.card-value {
  font-size: 36px;
  font-weight: 800;
  color: var(--primary);
  margin-bottom: 10px;
}

.card-change {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.positive {
  color: #10b981;
}

.negative {
  color: #ef4444;
}

.chart-container {
  background: white;
  border-radius: 20px;
  box-shadow: var(--card-shadow);
  padding: 30px;
  margin-bottom: 30px;
  height: 450px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
  position: relative;
}

.chart-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 22px;
  font-weight: 700;
  margin-bottom: 25px;
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 12px;
}

.analysis-container {
  background: white;
  border-radius: 20px;
  box-shadow: var(--card-shadow);
  padding: 30px;
  transition: var(--transition);
  border: 1px solid #e6f0ff;
}

.analysis-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 24px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f4ff;
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 700;
}

.analysis-content {
  line-height: 1.8;
  color: #444;
  font-size: 17px;
}

.insight-card {
  background: #f7faff;
  border-radius: 16px;
  padding: 20px;
  margin: 20px 0;
  border-left: 4px solid var(--primary);
}

.insight-title {
  font-weight: 700;
  color: var(--primary);
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.spinner-container {
  text-align: center;
  padding: 30px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border: 1px solid #e6f0ff;
}

.spinner-container p {
  margin-top: 20px;
  font-size: 18px;
  color: var(--primary);
  font-weight: 600;
}

/* API状态提示 */
.api-status {
  position: fixed;
  bottom: 20px;
  left: 20px;
  z-index: 1000;
}

.api-alert {
  padding: 12px 20px;
  background: var(--primary);
  color: white;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
  animation: fadeIn 0.3s ease-out;
}

.api-alert.error {
  background: var(--accent);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .video-header {
    flex-direction: column;
    text-align: center;
  }

  .video-cover {
    width: 100%;
    max-width: 400px;
  }

  .video-meta {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .metrics-cards {
    grid-template-columns: 1fr;
  }

  .logo {
    font-size: 2.2rem;
  }

  .video-title {
    font-size: 24px;
  }

  .chart-container {
    height: 350px;
    padding: 20px;
  }

  .back-button {
    padding: 8px 16px;
    font-size: 14px;
    top: 20px;
  }

  .header {
    padding-top: 50px;
  }

  .api-status {
    bottom: 10px;
    right: 10px;
    left: 10px;
  }

  .api-alert {
    width: calc(100% - 20px);
  }
}
</style>